package com.bey.keepgoing.webui.course;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.bey.keepgoing.model.Course;
import com.bey.keepgoing.service.course.CourseContext;

@Controller
@RequestMapping("/course")
public class CourseController {

	private CourseContext courseContext;

	@RequestMapping(value = "/course_add", method = RequestMethod.GET)
	public String addCourse(Model model) {
		model.addAttribute("course", new Course());
		return "course/course_add";
	}

	@RequestMapping(value = "/course_add", method = RequestMethod.POST)
	public String addCourseSubmit(@ModelAttribute("course") Course course,
			@RequestParam("file") MultipartFile file) {

		if (file.isEmpty()) {
			return "redirect:course_add_fail";
		}
		String fileName = file.getOriginalFilename();
		String fileExten = fileName.substring(fileName.lastIndexOf("."));
		Date date = new Date();
		long timestamp = date.getTime();
		course.setCourseImg(timestamp + fileExten);

		try {
			file.transferTo(new File("d:/temp/" + file.getOriginalFilename()));
		} catch (IllegalStateException e) {
			e.printStackTrace();
			return "redirect:course_add_fail";
		} catch (IOException e) {
			e.printStackTrace();
			return "redirect:course_add_fail";
		}

		courseContext.save(course);
		return "redirect:course_add_success";
	}

	@Autowired
	public void setCourseContext(CourseContext courseContext) {
		this.courseContext = courseContext;
	}

}
